package com.eascs.web.o2o.web.reward.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.eascs.app.dao.PageResult;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.tag.MenuTag;
import com.eascs.web.context.RequestContext;
import com.eascs.web.o2o.web.common.BaseMasterViewController;
import com.eascs.web.o2o.web.reward.entity.Province;
import com.eascs.web.o2o.web.reward.entity.RewardDataDic;
import com.eascs.web.o2o.web.reward.entity.SearchStaffForm;
import com.eascs.web.o2o.web.reward.service.BaseService;
import com.eascs.web.o2o.web.util.BankRowWriteHandler;

/**
 * 考核人员
 * @author EA
 *
 */
@Controller
@RequestMapping("/reward")
public class RewardViewController extends BaseMasterViewController {

	@Override
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "reward_personal");
	}
	
	@Inject
	BaseService baseService;
	
	@RequestMapping("/searchStaffInfo")
	public String searchStaffInfo(SearchStaffForm form){
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -1);
		String date=new SimpleDateFormat("yyyy-MM").format(c.getTime());
		String month = form.getTmonth()==null?date:form.getTmonth();
		form.setTmonth(month);
		PageResult<Object[]> pageResult = baseService.findPersonalInfo(form);
		String[] titles = new String[]{"考核月份","姓名","省区","入职时间","考核类型","省区所在梯队","起提点","当月考核系数","考核方案"};
		Button edit = ButtonHelper.createAjaxButton("编辑",
				"/reward/toEditStaff?userNo={9}&tmonth={0}");
		edit.setPermissionCode("rewardEditPerInfo");
		edit.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				if ("Y".equals(params[10])) {
						return false;
				} 
				return true;
			}
		});
		
		Button delete = ButtonHelper.createAjaxConfirmButton("删除", "/reward/delStaff?userNo={9}&t_month={0}");
		delete.setPermissionCode("rewardDelPerInfo"); // 权限按钮
		delete.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				if ("Y".equals(params[10])) {
						return false;
				} 
				return true;
			}
		});
		
		Button[] moreButtons = new Button[]{edit , delete};
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		paginationInfo.setBuildRowNumber(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setUrl(UrlUtil.resetParam(RequestContext.getRequestUrlWithQueryString(), "pageIndex", ""));
		paginationInfo.setMoreButtons(moreButtons);
		ViewContext.put("preMonth", month);
		ViewContext.put("paginationInfo", paginationInfo);
		updateDropdownBox();
		return "reward/staff_info";
	}
	
	@RequestMapping("/toAddStaff")
	public String addStaff(){
		updateDropdownBox();
		return "reward/add_staff";
	}
	
	
	private void updateDropdownBox(){
		List<Province> provinces = baseService.findAllEntity(Province.class);
		ViewContext.put("provinces", provinces);
		
		List<RewardDataDic> dics = baseService.findRewardDataDics();
		ViewContext.put("dics", dics);
	}
	
	@RequestMapping("/downloadStaff")
	public void downloadStaff(SearchStaffForm form , HttpServletResponse httpServletResponse,
			HttpServletRequest request){
		form.setPageSize(5000);
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -1);
		String date=new SimpleDateFormat("yyyy-MM").format(c.getTime());
		String month = form.getTmonth()==null?date:form.getTmonth();
		form.setTmonth(month);
		PageResult<Object[]> pageResult = baseService.downloadPersonalInfo(form);
		
		String path = RiskAmountController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/reward_staff_info.xls").toString();
		try {
			String outfile = "考核人员信息表.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes     = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists()) 
				throw new RuntimeIOException("file not found");

			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");

			// 开始的表格，行，列
			int sheetIndex  = 0;
			int rowIndex    = 1;
			int columnIndex = 0;
			// 包含的列
			int col = 12;
			// 需要统计的列
			int[]  arr = {};
			
			BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(pageResult.getData(), col, arr, null, sheetIndex, rowIndex, columnIndex);
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), RewardRestController.class.getResourceAsStream("/excelTemplate/reward_staff_info.xls"), bankRowWriteHandler);

		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} 		
	}	
}
